package com.xudm.cdg.interceptor;

import cn.hutool.core.collection.ArrayIter;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.CaseInsensitiveMap;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import com.xudm.cdg.utils.RequestAttrUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class LoginUtil {
    private static final ThreadLocal<String> VISITORID_THREAD_LOCAL = new ThreadLocal<>();
    public static final String VISITOR_KEY = "visitorId";

    public static String getLoginId() {
        String visitorId = VISITORID_THREAD_LOCAL.get();
        if (visitorId == null) {
            visitorId = getVisitorId();
            VISITORID_THREAD_LOCAL.set(visitorId);
        }
        return visitorId;
    }

    private static String getVisitorId() {
        HttpServletRequest request = RequestAttrUtil.getHttpServletRequest();
        // 从请求头中获取访问者id
        String visitorId = request.getHeader(VISITOR_KEY);
        if (visitorId == null) {
            // 从cookie里面获取 visitorId
            Cookie cookie = getCookie(request, VISITOR_KEY);
            visitorId = null == cookie ? null : cookie.getValue();
            if (visitorId == null) {
                // 从请求参数中获取 visitorId
                visitorId = request.getParameter(VISITOR_KEY);
            }
        }
        return visitorId;
    }

    public static Cookie getCookie(HttpServletRequest httpServletRequest, String name) {
        return readCookieMap(httpServletRequest).get(name);
    }

    public static Map<String, Cookie> readCookieMap(HttpServletRequest httpServletRequest) {
        Cookie[] cookies = httpServletRequest.getCookies();
        return ArrayUtil.isEmpty(cookies) ? MapUtil.empty() : IterUtil.toMap(new ArrayIter(httpServletRequest.getCookies()), new CaseInsensitiveMap(), Cookie::getName);
    }

    public static void removeVisitorId() {
        VISITORID_THREAD_LOCAL.remove();
    }
}
